import 'package:flutter/material.dart';
import '../../utils/Global.dart';
import '../../provider/UserProvider.dart';
import 'package:provider/provider.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../../provider/CurrentIndexProvider.dart';

class Login extends StatefulWidget {
  const Login({Key? key}):super(key: key);
  @override
  State<Login> createState() => _LoginState();
}

class _LoginState extends State<Login> {
  final GlobalKey<FormState> _formkey = GlobalKey<FormState>();
 
  String _phone = '';
  String _password = '';

  @override
  Widget build(BuildContext context) {
    UserProvider userProvider = Provider.of<UserProvider>(context);
    return Scaffold(
      appBar: AppBar(
        title: Text('用户登录'),
        centerTitle: true,
        automaticallyImplyLeading: false,
        leading: IconButton(
          icon: Icon(Icons.arrow_back, color: Colors.blue),
          onPressed: () {
             context.read<CurrentIndexProvider>().changeIndex(0);
             G.router?.navigateTo(context, '/');
          }),
      ), 
      body: Container(
        padding: EdgeInsets.all(20),
        child: Column(
          children: [
            Form(
              key: _formkey,
              child: Column(
                children: [
                  TextFormField(
                    decoration: InputDecoration(
                      hintText: '手机号'
                    ),
                    validator: (value) {
                      RegExp reg = new RegExp(r'^\d{11}$');
                      if(!reg.hasMatch(value!)) {
                        return '请输入正确的手机号';
                      }
                      return null;
                    },
                    onSaved: (value) {
                      print('$value 手机号');
                      _phone = value!;
                    },
                  ),
                  TextFormField(
                    decoration: InputDecoration(
                      hintText: '密码'
                    ),
                    validator: (value) {
                      return value!.length < 6 ? "密码长度不够": null;
                    },
                    onSaved: (value) {
                      print('_password onSaved');
                      _password = value!;
                    },
                  )
                ],
              )
            ),
            SizedBox(height: 50.h),
            Row(
              children: [
                Expanded(
                  child: 
                    ElevatedButton(
                      style: ButtonStyle(
                        minimumSize: MaterialStateProperty.all(Size(100, 50)), // 设置宽和高
                        backgroundColor: MaterialStateProperty.all(Color(0xffedfcf5)),
                         shape: MaterialStateProperty.all(BeveledRectangleBorder(borderRadius: BorderRadius.circular(4))),//圆角弧度
                      ),
                      child: Text('提交'),
                      onPressed: () async {
                        if(_formkey.currentState!.validate()) {
                          _formkey.currentState!.save();
                        }
                        // 调用登录接口
                        var res = await G.api.user.login(phone: _phone, password: _password);
                        print('$res 梅西登录');
                        if (res != false) {
                          print('登录成功');
                          userProvider.doLogin(res); // 修改用户的登录状态
                          Map userInfo = await G.api.user.getUerInfo();
                          print(userInfo);
                          userProvider.setUserInfo(userInfo); 
                          G.router?.pop(context);
                        } else {
                          print('登录失败');
                          _formkey.currentState?.reset();
                        }
                      },
                    ),
                ),
                SizedBox(
                  width: 20,
                ),
                Expanded(
                  child: 
                    ElevatedButton(
                      style: ButtonStyle(
                        backgroundColor: MaterialStateProperty.all(Color(0xffedfcf5)),
                        minimumSize: MaterialStateProperty.all(Size(0, 50)), // 设置宽和高
                         shape: MaterialStateProperty.all(BeveledRectangleBorder(borderRadius: BorderRadius.circular(4))),//圆角弧度
                      ),
                      child: Text('重置'),
                      onPressed: () async {
                        _formkey.currentState?.reset();
                      },
                    ),
                )
              ],
            )
          ],
        ),
      ),
    );
  }
}